using System.Configuration;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.IO;
using LinqRepositorySample.Domain;
using Rhinestone.Shared;

namespace LinqRepositorySample.Data.LinqToSql
{
    public class LinqUnitOfWorkFactory : IUnitOfWorkFactory
    {
        #region Implementation of IUnitOfWorkFactory
        public IUnitOfWork Create()
        {
            return new LinqUnitOfWork(LoadDataContext());
        }

        private DataContext LoadDataContext()
        {
            Stream mappings = GetType().Assembly.GetManifestResourceStream("LinqRepositorySample.Data.LinqToSql.mapping.xml");
            XmlMappingSource mappingSource = XmlMappingSource.FromStream(mappings);
            DataContext context = new DataContext(ConfigurationManager.ConnectionStrings["SampleDB"].ConnectionString,
                                              mappingSource);
            context.DeferredLoadingEnabled = false;
            DataLoadOptions loadOptions = new DataLoadOptions();
            loadOptions.LoadWith<Customer>(x => x.Orders);
            loadOptions.LoadWith<Order>(x => x.OrderDetails);
            loadOptions.LoadWith<OrderDetail>(x => x.Product);
            context.LoadOptions = loadOptions;
            return context;
        }
        #endregion
    }
}